<template>
  <div>
    <!-- 定义面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>博客管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增博客</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 定义卡片视图 -->
    <el-card class="box-card">
      <!-- 定义页面提示信息 -->
      <el-alert title="新增博客流程" type="info" effect="dark" center show-icon :closable="false"></el-alert>

      <!-- 定义步骤条 字符串需要转化为数值 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="博客信息"></el-step>
        <el-step title="标题图片"></el-step>
        <el-step title="博客内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 定义标签页 before-leave:切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
      <el-form
        :model="addBlogForm"
        :rules="addBlogFormRules"
        ref="addBlogFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeLeave">
          <el-tab-pane label="博客信息" name="0">
            <el-row>
              <el-col :span="20">
                <el-form-item label="博客标题" prop="title">
                  <el-input v-model="addBlogForm.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="博客简介" prop="summary">
                  <el-input v-model="addBlogForm.summary"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="博客分类" prop="blogSort">
                  <el-select v-model="blogSortUid" placeholder="请选择博客分类">
                    <el-option
                      v-for="item in blogSortList"
                      :key="item.uid"
                      :label="item.sortName"
                      :value="item.uid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="博客标签" prop="blogTag">
                  <el-select v-model="blogTagUids" placeholder="请选择博客标签" multiple>
                    <el-option
                      v-for="item in blogTagList"
                      :key="item.uid"
                      :label="item.content"
                      :value="item.uid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 实现图片上传 multiple支持多选文件 -->
          <el-tab-pane label="标题图片" name="1">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              multiple
              drag
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="博客内容" name="2">
            <!-- 定义富文本编辑器-->
            <quill-editor ref="myQuillEditor" :options="quillOption" v-model="blogDesc.blogDesc"></quill-editor>

            <!-- 定义添加商品按钮-->
            <el-button type="primary" class="addBlogBtnClass" @click="addBlogBtn">新增博客</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 定义图片展现对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
      <img :src="imageUrlPath" width="100%" height="100%" />
    </el-dialog>
  </div>
</template>

<script>
import quillConfig from '../../quillEditor/quill-config.js'
export default {
  data() {
    return {
      //富文本自定义配置
      quillOption: quillConfig,
      activeIndex: '0',
      addBlogForm: {
        title: '',
        summary: '',
        fileUid: ''
      },
      blogDesc: {
        blogDesc: ""
      },
      addBlogFormRules: {
        title: [{
          required: true,
          message: '请输入博客标题信息',
          trigger: 'blur'
        }],
        summary: [{
          required: true,
          message: '请输入博客简介信息',
          trigger: 'blur'
        }],
        blogSort: [{
          required: true,
          message: '请选择博客分类',
          trigger: 'blur'
        }],
        blogTag: [{
          required: true,
          message: '请选择博客标签',
          trigger: 'blur'
        }],
      },
      props: {
        expandTrigger: 'hover',
        value: "id", //选中数据的value值
        label: "name", //选中数据展现名称
        children: "children", //自选项数据
      },
      //设置商品动态参数
      dynamicTableData: [],
      staticTableData: [],
      //定义文件上传路径地址
      uploadUrl: "http://localhost:8091/file/upload",
      //定义图片网络访问地址
      imageUrlPath: "",
      //定义图片控制开关
      dialogImageVisible: false,
      //选中的博客分类id
      blogSortUid: "",
      //博客分类列表数据
      blogSortList: [],
      //选中的博客标签id
      blogTagUids: [],
      //博客标签列表数据
      blogTagList: [],
      //分页查询对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 100
      }
    }
  },
  created() {
    this.findblogSortList()
    this.findblogTagList()
  },
  methods: {
    //获取所有博客分类信息
    async findblogSortList() {
      const { data: result } = await this.$http.get('/blogsort/getList', {
        params: this.queryInfo,
      })
      if (result.status !== 200) return this.$message.error("博客分类列表查询失败")
      this.blogSortList = result.data.rows
    },
    //获取所有博客标签信息
    async findblogTagList() {
      const { data: result } = await this.$http.get('/tag/getList', {
        params: this.queryInfo,
      })
      if (result.status !== 200) return this.$message.error("博客标签列表查询失败")
      this.blogTagList = result.data.rows
      console.log(this.blogTagList)
    },
    //当标签页数据没有完成选择时 不让切换标签页
    beforeLeave(activeName, oldActiveName) {
      //注意oldActiveName的数据类型为字符串
      if (this.blogSortUid.length < 1 && oldActiveName === '0') {
        this.$message.error("请选择博客分类")
        return false
      }
      if (this.blogTagUids < 1 && oldActiveName === '0') {
        this.$message.error("请选择博客标签")
        return false
      }
    },
    //预览图片的方法
    handlePreview(file) {
      //获取图片的虚拟路径
      this.imageUrlPath = file.response.data.urlPath
      this.dialogImageVisible = true
    },
    //移除图片的方法
    async handleRemove(file) {
       this.addBlogForm.fileUid = ''
      /* //移除数组中的数据
      let virtualPath = file.response.data.virtualPath
      //通过findIndex函数 获取数组中指定数据的位置
      let index = this.addBlogForm.images.findIndex(x => x === virtualPath)
      //删除数组中指定的数据
      this.addBlogForm.images.splice(index, 1)
      //删除服务中的文件
      let {
        data: result
      } = await this.$http.delete("/file/deleteFile", {
        params: {
          virtualPath: virtualPath
        }
      })
      if (result.status !== 200) return this.$message.error("删除图片失败")
      this.$message.success("删除图片成功") */
    },
    //如果文件上传成功之后调用
    handleSuccess(response, file) {
      if (response.status !== 200) return this.$message.error("文件上传失败")
      file.name = response.data.fileName
      //获取虚拟路径
      let fileUid = response.data.fileUid
      console.log(fileUid);
      //将数据封装到Form表单中
      this.addBlogForm.fileUid = fileUid
    },

    /* 添加商品按钮 */
    async addBlogBtn() {
      /* let flag = true
      //1.完成表单校验
      this.$refs.addBlogFormRef.validate(valid => {
        if (!valid) {
          flag = valid;
          return this.$message.error("请输入博客必填项")
        }
      })
      if (!flag) {
        return
      } */

      //2.装填数据
      //this.addBlogForm.images = this.addBlogForm.images.join(",")

      let tagList = new Array();
      for (let i=0; i<this.blogTagUids.length;i++) {
          let tag = {
            uid: this.blogTagUids[i]
          }
          tagList.push(tag);
      }
      let username = window.sessionStorage.getItem("username");
      let uid = window.sessionStorage.getItem("uid");
      let blog = {
        title : this.addBlogForm.title,
        summary : this.addBlogForm.summary,
        blogSortUid: this.blogSortUid,
        tagList : tagList,
        content : this.blogDesc.blogDesc,
        author: username,
        adminUid: uid,
        fileUid: this.addBlogForm.fileUid
      }
      console.log(blog)
      let { data: result } = await this.$http.post("/blog/add", blog)
      if (result.status !== 200) return this.$message.error("博客新增失败")
      this.$message.success("博客新增成功")

      //2.5添加完成之后,将数据重定向到商品展现页面
      this.$router.push("/blog")
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}

.el-cascader {
  width: 30%;
}

/* 控制复选框的右边距5像素 !important 表示优先执行 IE6不兼容*/
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.addBlogBtnClass {
  margin-top: 15px;
}
</style>
